var a = document.documentElement.clientHeight - 72;
var b = document.documentElement.clientWidth - 25;
var clons = {};
$(function(){
	$('#parentTabPanel').window('setTitle','成本录入单');  // 给这个窗口set一个title
	// 加载按钮
	loadButns();
	// 初始化datagrid
	loadDategrid();
	// 加载条件查询的字段
	loadPages();
	// 加载对照表信息
	loadDzSource();
	// 加载dialog
	loadDialog();
});
// 加载节点的对照信息
function loadDzSource(){
	$.ajax({
		url:'../../dz/queryDzList',
		type:'post',
		data:{dzIds:'dz_project;dz_xt;dz_pdroduct;dz_finSubject;dz_bumen;dz_operators;dz_pay_type'},
		success:function(data){
			// project 项目 dzxt选题 product商品/材料 finsubject成本科目
			// bumen 部门 inputman 录入人 applyMan审核人 payType结算方式
			// payman 结算对象 yewuMan 业务对象 dailiMan 代理对象
			project = data[0];
			dzxt = data[1];
			product = data[2];
			finsubject = data[3];
			bumen = data[4];
			inputman = data[5];
			applyMan = data[5];
			payType = data[6];
			payman = data[5];
			yewuMan = data[5];
			dailiMan = data[5];
		}
	});
}
// 对照表信息赋值
function projectformatter(value){
	for(var i=0; i<project.length; i++){
		if (project[i].ID == value) return project[i].NAME;
	}
	return value;
}
function dzxtformatter(value){
	for(var i=0; i<dzxt.length; i++){
		if (dzxt[i].ID == value) return dzxt[i].NAME;
	}
	return value;
}
function productformatter(value){
	for(var i=0; i<product.length; i++){
		if (product[i].ID == value) return product[i].NAME;
	}
	return value;
}
function finsubjectformatter(value){
	for(var i=0; i<finsubject.length; i++){
		if (finsubject[i].ID == value) return finsubject[i].NAME;
	}
	return value;
}
function bumenformatter(value){
	for(var i=0; i<bumen.length; i++){
		if (bumen[i].ID == value) return bumen[i].NAME;
	}
	return value;
}
function inputmanformatter(value){
	for(var i=0; i<inputman.length; i++){
		if (inputman[i].ID == value) return inputman[i].NAME;
	}
	return value;
}
function applyManformatter(value){
	for(var i=0; i<applyMan.length; i++){
		if (applyMan[i].ID == value) return applyMan[i].NAME;
	}
	return value;
}
function payTypeformatter(value){
	for(var i=0; i<payType.length; i++){
		if (payType[i].ID == value) return payType[i].NAME;
	}
	return value;
}
function paymanformatter(value){
	for(var i=0; i<payman.length; i++){
		if (payman[i].ID == value) return payman[i].NAME;
	}
	return value;
}
function yewuManformatter(value){
	for(var i=0; i<yewuMan.length; i++){
		if (yewuMan[i].ID == value) return yewuMan[i].NAME;
	}
	return value;
}
function dailiManformatter(value){
	for(var i=0; i<dailiMan.length; i++){
		if (dailiMan[i].ID == value) return dailiMan[i].NAME;
	}
	return value;
}
// 加载按钮 传入参数butnId
function loadButns(){
	$.ajax({
		type:'post',
		url:'../../framework/buttonsList',
		data:{'butnId':'finCost'},
		success:function(data){
			if(data == ""){
				alert("按钮数据为空");
			}else{
				// 请求一个组织按钮的方法
				var buttons = data;
				var butHTML = "";
				for(var i = 0; i < buttons.length; i++){
					butHTML += formatButtons(buttons[i]);
				}
				$('#COSTBUTTONS').html(butHTML);
				$('#COSTQUERYBUT').html(butHTML);
				$.parser.parse();  // 重新编译界面
			}
		}
	})
}
// 加载datagrid 传入参数dsId(配置DS的数据源ID)；colId（//加载查询条件或当前界面的主表信息 传入参数colId）
function loadDategrid(){
//	$.ajax({
//		type:'post',
//		url:'../../framework/listQueryJson',
//		data:{'dsId':'FIN_COST','colId':'fin_cost','execFlag':'','flag':''},
//		success:function(data){
//			if(data==""){
//				alert("数据为空");
//			}else{
//				// 给datagrid赋列值，还有rows
//				mdatagrid(data);
//			}
//		}
//	})
	$.ajax({
        type:'post',
        url:'../../framework/loadColumnsU',
        data:{'colId':'fin_cost','type':'4'},
        success:function(data){
            if(data ==""){
                alert("数据为空");
            }else{
                producePage(data,'CostDataList','4','');
            	$('#CostDataList').datagrid({
            		onDblClickRow:function(rowIndex,rowData){
            			// 调用一个加载详情的方法
            			showUpdWin(rowData.COST_ID);
            			theLineIndex = rowIndex;
            		}
            	});
            }
        }
     });
	
}

// 组合datagrid信息 不用改任何信息
//function mdatagrid(data){ // 传入的是queryJson 里面就有columns和rows
//	var lastIndex;
//	$('#CostDataList').datagrid({
//		iconCls:'icon-save',
//		height:a,
//		width:b,
//		striped: true,				 
//		collapsible:true,
//		autoRowHeight: false,		
//		sortOrder: 'desc',
//		remoteSort: false,
//		pageList:[30,50,100,150],
//		columns:[[]],
//		pagination:true,
//		rownumbers:true,
//		singleSelect:true,
//		onDblClickRow:function(rowIndex,rowData){
//			// 调用一个加载详情的方法
//			showUpdWin(rowData.COST_ID);
//			theLineIndex = rowIndex;
//		}
//	});
//	var dataGrid = $('#CostDataList');
//	dataGrid.datagrid(jointColumn(data.columns));// 根据配置选项，生成datagrid
//}
var divName="";
// 加载查询条件或当前界面的主表信息 传入参数colId(界面配置的总DS_ID)
function loadPages(){
//	$.ajax({
//		type:'post',
//		url:'../../framework/columnList',
//		data:{'colId':'fin_cost'}, 
//		success:function(data){
//			if(data ==""){
//				alert("数据为空");
//			}else{
//				// 请求一个组织列的方法
//				clons = data;
//				divName='COSTQUERYCLN';
//				makeColumns(data,divName);
//			}
//		}
//	});
	$.ajax({
        type:'post',
        url:'../../framework/loadColumnsU',
        data:{'colId':'fin_cost','type':'3'},
        success:function(data){
            if(data ==""){
                alert("数据为空");
            }else{
                producePage(data,'COSTQUERYCLN','3','');
            }
        }
     });
}
// 查询按钮执行的方法
function findCost(){
	var configStr = parseConfig('COSTQUERYCLN');
	$('#queryConfig').html(parseConfigStr('COSTQUERYCLN'));
	$('#costTabPanel').tabs('select','成本录入单列表');
	// 加载shuju
	$.ajax({
		url:'../../framework/loadData',
		data:{dsId:'fin_cost',config:configStr},
		success:function(queryJson){
			$('#CostDataList').datagrid("loadData", queryJson);
			costdata = queryJson.rows;
			$('#CostDataList').datagrid({url:queryJson.url});
			$('#CostDataList').datagrid({
				 rowStyler:function(index,row){   
			        if (row.IS_VERIFY == 1){   
			            return 'background-color:#A9ff8c;';   
			        } 
			    } 
			});
		}
	});
}
// 添加按钮时的方法
function showAddWin(){
	if(addYWTab('costTabPanel',"添加成本录入单","<div style='padding:20px;'><div id='ADDCOSTBUT'></div><form id='addCOSTForm'><table id='addCOSTWin'></table></form></div>")!=1){
		divName='addCOSTWin';// 条件字段
		//makeColumns(clons,divName);
		$.ajax({
            type:'post',
            url:'../../framework/loadColumnsU',
            data:{'colId':'fin_cost','type':'1'},
            success:function(data){
                if(data ==""){
                    alert("数据为空");
                }else{
                    //请求一个组织列的方法
                    producePage(data,'addCOSTWin','1','');
                }
            }
         });
		$.ajax({
			type:'post',
			url:'../../framework/buttonsList',
			data:{'butnId':'finSaveCost'},
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#ADDCOSTBUT').html(butHTML);
					$.parser.parse('#ADDCOSTBUT');  // 重新编译界面
				}
			}
		});
	}
}
// 添加成本录入单
function addFinCost(){
	if(checkRequire('addCOSTForm')=='Success'){
		$.ajax({
			type:'post',
			url:'../../newfinCost/saveCost',
			data:$('#addCOSTForm').serialize(),
			success:function(data){
				if(data.msg == "success"){
					$('#addCOSTForm input[name=costId]').val(data.info);
					$.messager.alert("提示","保存成功");
				}else if(data.msg == "upsuccess"){
					$.messager.alert("提示","更新成功");
				}else if(data.msg == "fail"){
				 	$.messager.alert("提示","保存失败！","info");
				}else{
					$.messager.alert("提示",data.msg,"error");
				}
			}
		});
	}
}
var costId ;
var rowObj = {};
// 双击详情的时候
function showUpdWin(rowId){
	costId = rowId;
	var contentHTML = "<div style='padding:20px;'><div id='COSTPAGEBUT'></div><form id='upCOSTForm'><table id='upCOSTWin'></table></form><div id='abc' class='abc' ><div id='boximg' class='box'></div></div></div>";
	divName='upCOSTWin'
	var tmpC = 0;
	var okj = {};
	for(var i = 0; (i < costdata.length) && (tmpC ==0); i ++){
		if(costdata[i].COST_ID == costId){
			okj = costdata[i];
			rowObj = costdata[i];
			tmpC = 1;
		}
	}
	var butnId ="";
	if(addYWTab('costTabPanel',"成本录入单详情",contentHTML)!=1){
		// 加载字段\按钮
		//makeColumns(clons,divName);
		$.ajax({
            type:'post',
            url:'../../framework/loadColumnsU',
            data:{'colId':'fin_cost','type':'2'},
            success:function(data){
                
                if(data ==""){
                    alert("数据为空");
                }else{
                    //请求一个组织列的方法
                    producePage(data,'upCOSTWin','2','');
                 // 因为上述没有ajax 请求，所以可以直接找到每个录入框
            		// 动态加载对照值 动态填充 全部变灰 //为确保动态对照加载完毕，所以ajax请求不可用封装的方法
            		var dzIdstr = serializeEDIType(divName);
            		$.ajax({
            			url:'../../dz/queryDzList',  
            			type:'post',
            			data:{dzIds:dzIdstr},
            			success:function(data){
            				// 下拉框
            				fillSelect(divName,data);
            				fillInfo(divName,okj);
            				// 将字段变灰
            				readOnlyAll(divName);
            				$('#costID').val($('#upCOSTForm input[name=costId]').val());
            				
            				var isApply=$('#upCOSTForm input[name=isVerify]').val();
            				if(isApply == 2){
            					butnId = "baseApprove";
            					$('#abc').hide();
            				}else if(isApply == 0){
            					butnId = "finUpCost;finApplyCost";
            					$('#abc').hide();
            				}
            				if(isApply ==2 || isApply ==0){
            					loadButtons(butnId);
            				}
            				if(isApply == 1){
            					$.ajax({
            						type:'post',
            						url:'../../newfinCost/judgeStatus',
            						data:{'costId':costId},
            						success:function(value){
            							if(value.msg == 1){
            								butnId = "baseApprove";
            							}else if(value.msg == 0){
            								butnId = "finApplyCost";
            							}
            							loadButtons(butnId);
            						}
            					});	
            					$('#boximg').append("<img src='../../pages/images/sysimg/approved.png'></img>");
            					$('#abc').show();
            				}
            			}
            		});
                }
            }
         });
		
	}else{
		fillInfo(divName,okj);
		// 将字段变灰
		readOnlyAll(divName);
		var isApply=$('#upCOSTForm input[name=isVerify]').val();
		if(isApply == 2){
			butnId = "baseApprove";
			$('#abc').hide();
		}else if(isApply == 0){
			butnId = "finUpCost;finApplyCost";
			$('#abc').hide();
		}
		if(isApply ==2 || isApply ==0){
			loadButtons(butnId);
		}
		if(isApply ==  1){
			$.ajax({
				type:'post',
				url:'../../newfinCost/judgeStatus',
				data:{'costId':costId},
				success:function(value){
					if(value.msg == 1){
						butnId = "baseApprove";
					}else if(value.msg == 0){
						butnId = "finApplyCost";
					}
					loadButtons(butnId);
				}
			});	
			if($('#boximg').html() == '')
			$('#boximg').append("<img src='../../pages/images/sysimg/approved.png'></img>");
			$('#abc').show();
		}
	}
	var e =$('#costTabPanel').tabs('exists','修改成本录入单');
	if(e == true){
		$('#costTabPanel').tabs('close','修改成本录入单');
	}
	
}
function upFinCost(){
	divName='upCOSTTb';// 条件字段
	if(addYWTab('costTabPanel',"修改成本录入单","<div style='padding:20px;'><div id='UPCOSTBUT'></div><form id='updCostForm'><table id='upCOSTTb'></table></form></div>")!=1){
		// 加载字段按钮
		makeColumns(clons,divName);
		$.ajax({
			type:'post',
			url:'../../framework/buttonsListC',
			data:{'butnId':'finUpSave'}, // XTupSave;XTsaveS
			success:function(data){
				if(data == ""){
					alert("按钮数据为空");
				}else{
					var buttons = data;
					var butHTML = "";
					for(var i = 0; i < buttons.length; i++){
						butHTML += formatButtons(buttons[i]);
					}
					$('#UPCOSTBUT').html(butHTML);
					$.parser.parse('#UPCOSTBUT');  // 重新编译界面
				}
			}
		});
		var dzIdstr = serializeEDIType("upCOSTTb");
		$.ajax({
			url:'../../dz/queryDzList',
			type:'post',
			data:{dzIds:dzIdstr},
			success:function(data){
					// 下拉框
					fillSelect(divName,data);
					fillInfo(divName,rowObj);
					// 将部分字段变灰
					readOnlyPart(divName);
			}
		});
	}else{
		// 填充记录
		fillInfo(divName,rowObj);
		readOnlyPart(divName);
		
	}
	// 关闭这个数据的详情界面
	var e =$('#costTabPanel').tabs('exists','成本录入单详情');
	if(e == true){
		$('#costTabPanel').tabs('close','成本录入单详情');
	}
}
// 修改成本录入单后的保存
function upSaveCost(){
	if(checkRequire('updCostForm')=='Success'){
		$.ajax({
			type:'post',
			url:'../../newfinCost/saveCost',
			data:$('#updCostForm').serialize(),
			success:function(data){
				if(data.msg == "success"){
					$('#updCostForm input[name=costId]').val(data.info);
					$.messager.alert("提示","保存成功");
				}else if(data.msg == "upsuccess"){
					$.messager.alert("提示","更新成功");
				}else if(data.msg == "fail"){
				 	$.messager.alert("提示","保存失败！","info");
				}else{
					$.messager.alert("提示",data.msg,"error");
				}
			},
			error:function(data,msg,obj){$.messager.alert("提示",obj,"error");}
		});
	}
}

// 审核按钮的方法
function isApply(){
	var costId = $('#upCOSTForm input[name=costId]').val();
	$.ajax({
		type:'post',
		url:'../../newfinCost/updApply',
		data:{'costId':costId},
		success:function(data){
			if(data.msg =='success'){
				$.messager.alert('审核结果','审核成功！');
				var butnId = "";
				if(data.traState == 0){
					butnId = "finUpCost;finApplyCost";    //修改和审核         为0的时候表现为未审核
					$('#abc').hide();
				}else if(data.traState == 2){
					butnId = "baseApprove";
					$('#abc').hide();
				}else if(data.traState == 3){
					butnId = "baseApprove";
					$('#abc').hide();
				}else if(data.traState == 4){
					butnId = "finApplyCost";
					if($('##boximg').html == ""){   //
						
					}
					$('#boximg').append("<img tem='sh' src='../../pages/images/sysimg/approved.png'></img>");  //已审批  则出现图片
					$('#abc').show();
				}
				$.ajax({
					type:'post',
					url:'../../framework/buttonsListC',
					data:{'butnId':butnId},
					success:function(data){
						if(data == ""){
							$('#COSTPAGEBUT').html('');
						}else{
							var buttons = data;
							var butHTML = "";
							for(var i = 0; i < buttons.length; i++){
								butHTML += formatButtons(buttons[i]);
							}
							$('#COSTPAGEBUT').html(butHTML);
							$.parser.parse('#COSTPAGEBUT');  // 重新编译按钮
						}
					}
				});
				var selectRow = $('#CostDataList').datagrid('getSelected');
				selectRow.IS_VERIFY= data.traState;
				$('#CostDataList').datagrid('refreshRow',theLineIndex);
			}else if(data.msg='fail'){
				$.messager.alert('审核结果','审核失败！');
			}
		}
	})	
}
function baseApprove(){
	var codeId = $('#costID').val();
	$("#costDialog").dialog('open');
	$('#logapply').load('../../approve/approveDJ',{'djId':codeId});
}

function loadDialog(){
	$("#costDialog").dialog({
		width:850,
		height:550,
		maximized:true,
		collapsible: true,
		maximizable: true,
		title:'单据审批',
		left:150,
		top:10
	});
	$("#costDialog").dialog('close');
}
function showQuery(){
	$('#costTabPanel').tabs('select',"条件查询");
	$('#queryCB').removeAttr('checked');
}